package com.yu.crm.ws;

import com.yu.crm.domain.pojo.CrmEigenvalue;
import com.yu.crm.service.impl.CrmEigenvalueService;
import com.yxzz.common.helper.JsonHelpers;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import javax.websocket.*;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;
import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

@ServerEndpoint(value = "/webSocketClientPW/{sid}")
@Component
@Log4j2
public class WebSockertClientPW {


    //  这里使用静态，让 service 属于类
    private static CrmEigenvalueService crmEigenvalueService;

    // 注入的时候，给类的 service 注入
    @Autowired
    public void setChatService(CrmEigenvalueService crmEigenvalueService) {
        WebSockertClientPW.crmEigenvalueService = crmEigenvalueService;
    }

    private int sum;
    private int new_sum;


    /**
     * 用于存所有的连接服务的客户端，这个对象存储是安全的
     */
    private static ConcurrentHashMap<String, WebSockertClientPW> webSocketMap = new ConcurrentHashMap<>();

    //当前会话
    private Session session;

    //当前sid
    private String sid;

    @OnOpen
    public void onOpen(Session session, @PathParam(value = "sid") String sid) {
        this.session = session;
        this.sid = sid;
        log.info("------------------sid" + sid);
        log.info("===================session" + session);
        // name是用来表示唯一客户端，如果需要指定发送，需要指定发送通过name来区分
        webSocketMap.put(sid, this);
        onOpen();
        log.info("WS 连接成功, sid={}, 在线数量={}", sid, webSocketMap.size());

    }

    @OnClose
    public void OnClose() {
        webSocketMap.remove(this.sid);
        log.info("[WebSocket] 退出成功，当前连接人数为：={}", webSocketMap.size());
    }

    @OnMessage
    public void OnMessage(String message) {
        log.info("[WebSocket] 收到消息：{}", message);
        start();
    }

    /**单发**/
    public void sendMessage(Object object) {
        String json = JsonHelpers.toJson(object).get();
        log.info("发送的数据" + json);
        try {
            webSocketMap.get(sid).session.getBasicRemote().sendText(json);
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }

    public void onOpen() {
        //获取总数
        sum = crmEigenvalueService.count();
        System.out.println("========" + sum);
        CrmEigenvalue queryInfo = new CrmEigenvalue();
        //只查今天的
        DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
        queryInfo.setStartDate(format.format(new Date()));
        List<CrmEigenvalue> crmEigenvalueList = crmEigenvalueService.listByQueryInfo(queryInfo);
        System.out.println("===========" + crmEigenvalueList.size());
        sendMessage(crmEigenvalueService.listByQueryInfo(queryInfo));
    }


    public void start() {
        new_sum = crmEigenvalueService.count();
        if (sum > new_sum) {
            //流水统计出现问题
            sendMessage("reload");
        }
        if (sum != new_sum) {

            CrmEigenvalue queryInfo = new CrmEigenvalue();
            //只查今天的
            DateFormat format = new SimpleDateFormat("yyyy-MM-dd");
            queryInfo.setStartDate(format.format(new Date()));
            //查询多出来的几条记录
            queryInfo.setLimit(new_sum - sum);
            sendMessage(crmEigenvalueService.listByQueryInfo(queryInfo));
            sum = new_sum;
        }

    }
}







